layui.use(['table', 'admin', 'form', 'ax', 'ztree'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var $ZTree = layui.ztree;
    var form = layui.form;

    /**
     * 系统管理--分类管理
     */
    var Category = {
        tableId: "categoryTable",
        condition: {
            categoryId: "",
            level:0
        }
    };

    /**
     * 初始化表格的列
     */
    Category.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'categoryId', hide: true, sort: true, title: 'id'},
            {field: 'name', sort: true, title: '分类名称'},
            {field: 'level', sort: true, title: 'level'},
            {field: 'sort', sort: true, title: '排序'},
            {field: 'description', sort: false, title: '备注'},
            {field: 'picture', sort: false, title: '图片'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 200}
        ]];
    };

    /**
     * 初始化表格的列
     */
    Category.initColumnLevel = function () {
        return [[
            {type: 'checkbox'},
            {field: 'categoryId', hide: true, sort: true, title: 'id'},
            {field: 'name', sort: true, title: '分类名称'},
            {field: 'level', sort: true, title: 'level'},
            {field: 'autoStatus', sort: true, title: '是否自动'},
            {field: 'cardNOLength', sort: true, title: '卡号长度'},
            {field: 'cardPasswordLength', sort: false, title: '卡密长度'},
            {field: 'cardRemark', sort: false, title: '卡类备注'},
            {field: 'sellStatus', sort: true, templet: '#sellTpl', title: '是否上架'},
            {field: 'hot', sort: true, templet: '#hotTpl', title: '是否热门'},
            {fixed: 'right', toolbar: '#tableBar', width:300, title: '操作', minWidth: 300}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Category.search = function () {
        var queryData = {};
        queryData['condition'] = $("#name").val();
        queryData['categoryId'] = Category.condition.categoryId;
        table.reload(Category.tableId, {where: queryData});
    };

    /**
     * 选择部门时
     */
    Category.onClickDept = function (e, treeId, treeNode) {
        if(treeNode.level >= 2) {
            table.render({
                elem: '#' + Category.tableId,
                url: Feng.ctxPath + '/category/list',
                page: true,
                height: "full-158",
                cellMinWidth: 100,
                cols: Category.initColumnLevel(),
                where: { //设定异步数据接口的额外参数，任意设
                    condition: $("#name").val()
                    ,categoryId: treeNode.id
                }
            });
        } else{
            table.render({
                elem: '#' + Category.tableId,
                url: Feng.ctxPath + '/category/list',
                page: true,
                height: "full-158",
                cellMinWidth: 100,
                cols: Category.initColumn(),
                where: { //设定异步数据接口的额外参数，任意设
                    condition: $("#name").val()
                    ,categoryId: treeNode.id
                }
            });
        }
        Category.condition.categoryId = treeNode.id;
        /*Category.search();*/
    };

    /**
     * 弹出添加
     */
    Category.openAddDept = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            area: ['600px'],
            title: '添加分类',
            content: Feng.ctxPath + '/category/category_add?pid=' + Category.condition.categoryId,
            end: function () {
                admin.getTempData('formOk') && table.reload(Category.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    Category.exportExcel = function () {
        var checkRows = table.checkStatus(Category.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑分类
     *
     * @param data 点击按钮时候的行数据
     */
    Category.onEditDept = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            area: ['600px'],
            title: '修改分类',
            content: Feng.ctxPath + '/category/category_update?categoryId=' + data.categoryId,
            end: function () {
                admin.getTempData('formOk') && table.reload(Category.tableId);
            }
        });
    };

    /**
     * 点击设置获取方式
     *
     * @param data 点击按钮时候的行数据
     */
    Category.onGetContent = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            area: ['600px', '500px'],
            title: '设置获取方式',
            content: Feng.ctxPath + '/category/get-content?categoryId=' + data.categoryId,
            end: function () {
                admin.getTempData('formOk') && table.reload(Category.tableId);
            }
        });
    };

    /**
     * 点击删除分类
     *
     * @param data 点击按钮时候的行数据
     */
    Category.onDeleteDept = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/category/delete", function () {
                Feng.success("删除成功!");
                table.reload(Category.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("categoryId", data.categoryId);
            ajax.start();
            window.location.reload(true)
        };
        Feng.confirm("是否删除分类 " + data.name + "?", operation);
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Category.onSetchannel = function (data) {
        window.location.href = Feng.ctxPath + '/pinChannel?categoryId=' + data.categoryId;
    };

    /**
     * 点击缓存
     *
     * @param data 点击按钮时候的行数据
     */
    Category.initCache = function (data) {
        var operation = function () {
            var loading = parent.layer.msg('loading', {icon: 16, shade: 0.3, time:0});
            var ajax = new $ax(Feng.ctxPath + "/category/init", function (data) {
                Feng.success("成功!");
                table.reload(Category.tableId);
                parent.layer.close(loading);
            }, function (data) {
                parent.layer.close(loading);
                Feng.error("失败!" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Feng.confirm("确定是否所有分类已经修改完毕?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Category.tableId,
        url: Feng.ctxPath + '/category/list',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: Category.initColumn()
    });

    /**
     * 修改状态
     *
     * @param id 分类id
     * @param checked 是否选中（1,2），选中就是启用，未选中就是禁用
     */
    Category.changeStatus = function (id, checked) {
        var ajax = new $ax(Feng.ctxPath + "/category/hot", function (data) {
            Feng.success("成功!");
        }, function (data) {
            Feng.error("失败!");
            table.reload(Category.tableId);
        });
        ajax.set("categoryId", id);
        ajax.set("hot", checked);
        ajax.start();
    };

    /**
     * 修改上下架状态
     *
     * @param id 分类id
     * @param checked 是否选中（1,2），选中就是启用，未选中就是禁用
     */
    Category.changeSellStatus = function (id, checked) {
        var ajax = new $ax(Feng.ctxPath + "/category/sell-status", function (data) {
            Feng.success("成功!");
        }, function (data) {
            Feng.error("失败!");
            table.reload(Category.tableId);
        });
        ajax.set("categoryId", id);
        ajax.set("sellStatus", checked);
        ajax.start();
    };

    //初始化左侧部门树
    var ztree = new $ZTree("categoryTree", "/category/tree");
    ztree.bindOnClick(Category.onClickDept);
    ztree.init();

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Category.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Category.openAddDept();
    });

    // 初始化面值缓存
    $('#btnInitCache').click(function () {
        Category.initCache();
    });

    // 导出excel
    $('#btnExp').click(function () {
        Category.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Category.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Category.onEditDept(data);
        } else if (layEvent === 'delete') {
            Category.onDeleteDept(data);
        } else if(layEvent === 'setContent') {
            Category.onGetContent(data);
        } else if (layEvent === 'setChannel') {
            Category.onSetchannel(data);
        }
    });

    // 修改状态
    form.on('switch(hot)', function (obj) {
        var id = obj.elem.value;
        var checked = obj.elem.checked ? 1 : 2;

        Category.changeStatus(id, checked);
    });

    // 修改上架状态
    form.on('switch(sell)', function (obj) {
        var id = obj.elem.value;
        var checked = obj.elem.checked ? 1 : 0;
        Category.changeSellStatus(id, checked);
    });

});
